﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ET.Monitor.DAL
{
    public class ReportDAL
    {
        object obj = null, dlVal = null;
        string strSql = "", strErrMsg = "";
        DataTable dt = new DataTable();
        IList<Hashtable> list = new List<Hashtable>();

        InvokeWebService iw = new InvokeWebService();
        string rtdbRelationAddress = "";
        string rtdbRealTimeAddress = "";
        string rtdbNameSpace = "";
        string rtdbJudge = "";
        public ReportDAL()
        {
            rtdbRelationAddress = ConfigurationManager.ConnectionStrings["RelationURL"].ConnectionString;
            rtdbRealTimeAddress = ConfigurationManager.ConnectionStrings["RealTimeURL"].ConnectionString;
            rtdbNameSpace = ConfigurationManager.ConnectionStrings["NameSpace"].ConnectionString;
            rtdbJudge = ConfigurationManager.ConnectionStrings["Judge"].ConnectionString;
        }

        #region 操作票分页
        public int GetTotalCount(string type, string state, string id)
        {
            string sqlWhere = "";

            if (id == "")
                sqlWhere = " where ";
            else
                sqlWhere = " where T_ORGID = '" + id + "' ";

            if (sqlWhere != "")
                if (type != "")
                    sqlWhere += " and T_TYPE='" + type + "'";
                else
                    sqlWhere += " T_TYPE='" + type + "'";


            //if (sqlWhere != "")
            //    if (type != "")
            //        sqlWhere += " and T_STATE='" + state + "' ";
            //    else
            //        sqlWhere += " T_STATE='" + state + "' ";

            strSql = @"select count(*) from T_FORM_TABLE" + sqlWhere;

            return (int)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunRowCount", new object[] { strSql, strErrMsg });
        }
        public DataTable GetForm(int count, int pageIndex, string type, string state, string id, DateTime st, DateTime et)
        {
            string sqlWhere = "";

            if (id == "")
                sqlWhere = " where T_TIME between '" + st + "' and '" + et + "' ";
            else
                sqlWhere = " where T_TIME between '" + st + "' and '" + et + "' and T_ORGID = '" + id + "' ";

            if (sqlWhere != "")
                if (type != "")
                    sqlWhere += " and T_TYPE='" + type + "'";
                else
                    sqlWhere += " T_TYPE='" + type + "'";


            //if (sqlWhere != "")
            //    if (type != "")
            //        sqlWhere += " and T_STATE='" + state + "' ";
            //    else
            //        sqlWhere += " T_STATE='" + state + "' ";

            strSql = @"select top " + count + " ID_KEY,T_TITLE,T_TIME, case when T_TYPE=0 then '操作票' when T_TYPE=1 then '电气一种票'  when T_TYPE=2 then '电气二种票' else '运行日志' end as T_TYPE,case T_STATE when 0 then '未完成' else '已完成' end T_STATE from T_FORM_TABLE where ID_KEY not in(select top " + ((pageIndex - 1) * count) + " ID_KEY from T_FORM_TABLE " + sqlWhere + " order by ID_KEY desc) and T_TIME between '" + st + "' and '" + et + "' and T_ORGID ='" + id + "' and T_TYPE ='" + type + "'  order by ID_KEY desc";

            return (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region  操作票
        public bool AddOperation(string stationID, string title, string order, string flr, string slr, DateTime time, string st, string et, int operation1, int operation2, int operation3, string rw, string bz, string car, string jhr, string ywk, string orders, string names, string states)
        {
            strSql = @"INSERT INTO T_FORM_TABLE (T_TITLE,T_TYPE,T_STATE,T_TIME,T_ORGID) VALUES('" + title + "','0','0','" + DateTime.Now + "','" + stationID + "')";

            bool judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });

            strSql = "select top 1 ID_KEY from T_FORM_TABLE order by ID_KEY desc";

            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });

            strSql = @"INSERT INTO T_FORM_OPERATIONORDER (T_FORMID,编号,发令人,受令人,发令时间,操作开始时间,操作结束时间,监护下操作,单人操作,检修人员操作,操作任务,备注,操作人,监护人,运维负责人)
     VALUES('" + obj + "','" + order + "','" + flr + "','" + slr + "','" + time + "','" + st + "','" + et + "','" + operation1 + "','" + operation2 + "','" + operation3 + "','" + rw + "','" + bz + "','" + car + "','" + jhr + "','" + ywk + "')";
            judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });

            string[] or = orders.Split('*');
            string[] nm = names.Split('*');
            string[] se = states.Split('*');
            strSql = "";
            for (int i = 0; i < or.Length; i++)
            {
                strSql += @"INSERT INTO T_FORM_OPERATION(T_ORDER,T_CONTENT,T_STATE,T_OTERATIONID) VALUES('" + or[i] + "','" + nm[i] + "','" + se[i] + "','" + obj + "');";
            }
            judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });

            return judge;
        }

        #endregion

        #region 工作票录入
        public bool AddOperation(string stationId, int type, string connect, DateTime time)
        {
            string title = "";
            if (type == 0)
                title = "操作票";
            if (type == 1)
                title = "电气一种票";
            if (type == 2)
                title = "电气二种票";
            if (type == 4)
                title = "运行日志";
            strSql = @"INSERT INTO T_FORM_TABLE(T_TITLE, T_TYPE, T_STATE, T_TIME, T_ORGID,T_CONNECT) VALUES('" + title + "', '" + type + "', '0', '" + DateTime.Now + "', '" + stationId + "','" + connect + "')";
            bool judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
            return judge;
        }
        #endregion

        #region 获取某张工作票
        public object GetOpeation(int id)
        {
            strSql = "select T_CONNECT from T_FORM_TABLE where ID_KEY='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            return obj;
        }
        #endregion

        #region 编辑工作票内容
        public bool UpdateOpeation(int id, string connect)
        {
            strSql = @"UPDATE T_FORM_TABLE SET T_CONNECT='" + connect + "' WHERE ID_KEY='" + id + "'";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 电量报表
        public List<double[]> GetElecHisVal(string id, DateTime time)
        {
            List<double[]> list = new List<double[]>();
            string column = "";
            string[] points = null;
            double[] val = null;

            column = "T_ELECTAG,T_ETPJTAG ,T_ETPFTAG,T_ETPPTAG,T_ETPGTAG,T_FETPTAG,T_FETPJTAG,T_FETPFTAG,T_FETPPTAG,T_FETPGTAG,T_EQTTTAG,T_EQTJTAG,T_EQTFTAG,T_EQTPTAG,T_EQTGTAG,T_FEQTTTAG,T_FEQTJTAG,T_FEQTFTAG,T_FEQTPTAG,T_FEQTGTAG";

            if (column != "")
            {
                List<string> _points = new List<string>();
                column = column.Substring(0, column.Length - 1);

                string str_order = id.Replace("(", "").Replace(")", "").Replace("'", "");

                strSql = "select " + column + " from T_BASE_POINTS_ORG where T_ORGID in(" + id + ") order by CHARINDEX(',' + LTRIM(T_ORGID) + ',', '," + str_order + ",')";

                dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
                if (dt != null && dt.Rows.Count > 0)
                {
                    points = new string[dt.Rows.Count];
                    val = new double[dt.Rows.Count];
                    for (int i = 0; i < id.Trim().Split(',').Length; i++)
                    {
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            _points.Add(dt.Rows[k][i].ToString());

                        }
                    }

                    val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValues", new object[] { _points.ToArray(), time });

                    List<double> list_val = new List<double>(val);

                    for (int i = 0; i < id.Trim().Split(',').Length; i++)
                    {
                        val = new double[dt.Rows.Count];
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            val[k] = list_val[0];
                            list_val.RemoveAt(0);
                        }
                        list.Add(val);
                    }
                }
            }
            return list;
        }

        #endregion

        #region 逆变器报表  日发电量、日转换效率、日等价发电时、性能比、光伏转换效率、最大直流电流、最大直流功率、最大交流功率
        public List<double[]> GetInverterHisVal(string id, DateTime sTime, DateTime eTime)
        {
            List<double[]> list = new List<double[]>();
            string column = "";
            string[] points = null;
            double[] val = null;

            column = "T_ELECDTAG,T_DZHXLTAG,T_DFDSTAG,T_XNBTAG,T_ZHLTAG";

            if (column != "")
            {
                List<string> _points = new List<string>();
                column = column.Substring(0, column.Length - 1);

                string str_order = id.Replace("(", "").Replace(")", "").Replace("'", "");

                strSql = "select " + column + " from T_BASE_POINTS_UNIT where T_UNITID in(" + id + ") order by CHARINDEX(',' + LTRIM(T_UNITID) + ',', '," + str_order + ",')";

                dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
                if (dt != null && dt.Rows.Count > 0)
                {
                    points = new string[dt.Rows.Count];
                    val = new double[dt.Rows.Count];
                    for (int i = 0; i < id.Trim().Split(',').Length; i++)
                        for (int k = 0; k < dt.Rows.Count; k++)
                            _points.Add(dt.Rows[k][i].ToString());

                    val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValues", new object[] { _points.ToArray(), eTime });

                    List<double> list_val = new List<double>(val);

                    for (int i = 0; i < id.Trim().Split(',').Length; i++)
                    {
                        val = new double[dt.Rows.Count];
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            val[k] = list_val[0];
                            list_val.RemoveAt(0);
                        }
                        list.Add(val);
                    }
                }
            }

            column = "T_IACRTAG,T_POWERTAG,T_DCPTAG";

            if (column != "")
            {
                List<string> _points = new List<string>();
                column = column.Substring(0, column.Length - 1);

                string str_order = id.Replace("(", "").Replace(")", "").Replace("'", "");

                strSql = "select " + column + " from T_BASE_POINTS_UNIT where T_UNIT in(" + id + ") order by CHARINDEX(',' + LTRIM(T_UNIT) + ',', '," + str_order + ",')";

                dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
                if (dt != null && dt.Rows.Count > 0)
                {
                    points = new string[dt.Rows.Count];
                    val = new double[dt.Rows.Count];
                    for (int i = 0; i < id.Trim().Split(',').Length; i++)
                        for (int k = 0; k < dt.Rows.Count; k++)
                            _points.Add(dt.Rows[k][i].ToString());

                    val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetMaxValue", new object[] { _points.ToArray(), sTime, eTime });

                    List<double> list_val = new List<double>(val);

                    for (int i = 0; i < id.Trim().Split(',').Length; i++)
                    {
                        val = new double[dt.Rows.Count];
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            val[k] = list_val[0];
                            list_val.RemoveAt(0);
                        }
                        list.Add(val);
                    }
                }
            }
            return list;
        }
        #endregion


        #region 文件下载
        public DataTable GetFile(int id)
        {
            DataTable dt = new DataTable();
            string strSql = "select * from T_INFO_FILE where ID_KEY='" + id + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            return dt;
        }

        #endregion

        #region 文件删除
        public bool DeleteFile(int id)
        {
            DataTable dt = new DataTable();
            string strSql = "delete  from T_INFO_FILE where ID_KEY='" + id + "'";
           
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
           
        }

        #endregion


        public DataTable SearchFile(string id,DateTime st ,DateTime et)
        {
            DataTable dt = new DataTable();
            string strSql = "select * from T_INFO_FILE where T_ORGID='" + id + "' and (T_TIME between '"+ st + "' and  '" + et + "') order by T_TIME";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            return dt;
        }

        #region  文件上传
        public bool UpLoaFile(string org_id,string name, DateTime time, int filetype, string type, byte[] file)
        {
            DataTable dtxml = new DataTable();
            DataColumn dc = new DataColumn("key", Type.GetType("System.String"));
            dtxml.Columns.Add(dc);
            dc = new DataColumn("value", Type.GetType("System.String"));
            dtxml.Columns.Add(dc);
            DataRow dr = dtxml.NewRow();
            dr["key"] = "T_ORGID";
            dr["value"] = org_id;
            dtxml.Rows.Add(dr);

            dr = dtxml.NewRow();
            dr["key"] = "T_NAME";
            dr["value"] = name;
            dtxml.Rows.Add(dr);

            dr = dtxml.NewRow();
            dr["key"] = "T_TIME";
            dr["value"] = time;
            dtxml.Rows.Add(dr);

            dr = dtxml.NewRow();
            dr["key"] = "T_FILETYPE";
            dr["value"] = filetype;
            dtxml.Rows.Add(dr);

            dr = dtxml.NewRow();
            dr["key"] = "T_TYPE";
            dr["value"] = type;
            dtxml.Rows.Add(dr);

            DataSet ds = new DataSet();
            ds.Tables.Add(dtxml);

            bool judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "UpDocument", new object[] { ds, "T_INFO_FILE", "T_CONNECT", file });
            return judge;
        }
        #endregion

        #region 文件上传 类型        
        public DataTable GetFileType()
        {
            strSql = @"select T_FILEID,T_FILENAME,T_PARENTID from T_INFO_FILETYPE";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dt;
        }
        #endregion

    }
}